//
//  ControlCategory.m
//  MoneyIndividual
//
//  Created by Le Anh Tai on 12/28/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "ControlCategory.h"
#import "Utility.h"

@implementation UILabel(Extension)

+ (UILabel *)newTitleLabel
{
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor clearColor];
    label.font = FONT(FONT_SIZE_TITLE);
    return label;
}

+ (UILabel *)newDescriptionLabel
{
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor clearColor];
    label.font = FONT(FONT_SIZE_DESCRIPTION);
    label.textColor = COLOR_GRAY_DARK;
    return label;
}

+ (UILabel *)newNormalLabel
{
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor clearColor];
    label.font = FONT(FONT_SIZE_NORMAL);
    return label;
}

- (int)fontHeight
{
    return [Utility getLineHeightOfFont:self.font];
}

- (float)widthString
{
    return [Utility getSizeOfString:self.text font:self.font size:CGSizeMake(999, 999) lineBreakMode:self.lineBreakMode].width;
}

@end

@implementation UIButton(Extension)

+ (UIButton*)buttonWithTitle:(NSString*)title target:(id)target selector:(SEL)sel
{
    UIButton *button = [UIButton buttonWithTarget:target selector:sel];
    [button setTitle:title forState:UIControlStateNormal];
    
    float widthString = [button.titleLabel widthString];
    button.frame = RECT(0, 0, widthString, HEI_HEADER_VIEW);
    
    return button;
}

+ (UIButton*)buttonWithImage:(UIImage*)image target:(id)target selector:(SEL)sel
{
    UIButton *button = [UIButton buttonWithTarget:target selector:sel];
    [button setImage:image forState:UIControlStateNormal];
    
    return button;
}

+ (UIButton*)buttonWithTarget:(id)target selector:(SEL)sel
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitleColor:COLOR_BLUE_IOS_7 forState:UIControlStateNormal];
    [button setTitleColor:COLOR_BLUE_DARK forState:UIControlStateHighlighted];
    [button addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

@end

@implementation UIImage(Extension)

+ (UIImage *)imageNamed:(NSString *)name color:(UIColor *)color
{
    UIImage *image = [UIImage imageNamed:name];
    
    return [image imageTintedWithColor:color];
}

- (UIImage *)imageTintedWithColor:(UIColor *)color
{
	if (color)
    {
		// Construct new image the same size as this one.
		UIImage *image;
		UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
		CGRect rect = CGRectZero;
		rect.size = [self size];
		
		// tint the image
		[self drawInRect:rect];
		[color set];
		UIRectFillUsingBlendMode(rect, kCGBlendModeDarken);
		
		// restore alpha channel
		[self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
		
		image = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
		
		return image;
	}
	
	return self;
}

+ (UIImage *)imageFromColor:(UIColor *)color withRect:(CGRect)imageRect
{
    UIGraphicsBeginImageContext(imageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, imageRect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

+ (UIImage *)imageFromColor:(UIColor *)color
{
    CGRect rect = RECT(0, 0, 1, 1);
    return [UIImage imageFromColor:color withRect:rect];
}
@end

@implementation UIView(Extension)

+ (UIView *)newLineView
{
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = COLOR_GRAY_LIGHT;
    return lineView;
}

@end

@implementation UITextField(Extension)

- (float)floatValue
{
    if (self.text.length == 0)
    {
        return 0;
    }
    
    return [self.text floatValue];
}

- (void)becomeFirstResponderAfterDelay
{
    [self performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.25];
}

//- (void)setInputViewEx:(UIView *)inputViewEx
//{
//    UIView *accessoryView = self.inputAccessoryView;
//    
//    inputViewEx.top = accessoryView.bottom;
//    
//    UIView *inputView = [[UIView alloc] init];
//    inputView.frame = RECT(0, 0, inputViewEx.width, inputViewEx.bottom);
//    [inputView addSubview:accessoryView];
//    [inputView addSubview:inputViewEx];
//    
//    self.inputAccessoryView = nil;
//    self.inputView = inputView;
//}

@end

@implementation UINavigationController(Extension)

+ (UINavigationController *)newNavigationWithRoot:(UIViewController *)viewController
{
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    
    navigationController.navigationBar.tintColor = COLOR_WHITE_PURE;
    
    navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                              COLOR_BLACK_PURE,UITextAttributeTextColor,
                                                              COLOR_WHITE_PURE,UITextAttributeTextShadowColor,nil];
    
    return navigationController;
}

@end

@implementation NSString(Extension)

+(NSString*)stringWithInt:(NSInteger)intValue
{
    return [NSString stringWithFormat:@"%d", intValue];
}

- (RepeatType)getRepeatTypeByRepeatTypeString:(NSString*)type
{
    if (type == nil || [type isKindOfClass:[NSString class]] == NO)
    {
        return RepeatTypeNone;
    }
    if ([type isEqualToString:REPEAT_DAILY]) return RepeatTypeDaily;
    if ([type isEqualToString:REPEAT_WEEKLY]) return RepeatTypeWeekly;
    if ([type isEqualToString:REPEAT_EACH_2_WEEK]) return RepeatTypeEach2Week;
    if ([type isEqualToString:REPEAT_MONTHLY]) return RepeatTypeMonthly;
    
    return RepeatTypeNone;
}
@end

@implementation NSManagedObject(Extension)

- (BOOL)containKey:(NSString *)key
{
    BOOL hasFoo = [[self.entity propertiesByName] objectForKey:key] != nil;
    return hasFoo;
}

- (id)valueForKeyEx:(NSString *)key
{
    if ([self containKey:key])
    {
        return [self valueForKey:key];
    }
    
    return nil;
}

- (void)setValueEx:(id)value forKey:(NSString *)key
{
    if ([self containKey:key])
    {
        [self setValue:value forKey:key];
    }
}

- (NSManagedObject *)getAccountOfTransactionObject
{
    NSManagedObject *catalog = [self valueForKeyEx:CATALOG_KEY];
    if (catalog)
    {
        return [catalog valueForKeyEx:ACCOUNT_KEY];
    }
    
    return nil;
}

- (void)setAccountForTransactionObject:(NSManagedObject *)account
{
    NSManagedObject *catalog = [self valueForKeyEx:CATALOG_KEY];
    if (catalog && account)
    {
        [catalog setValueEx:account forKey:ACCOUNT_KEY];
    }
}

- (NSString*)getRepeatTypeString
{
    NSNumber *type = [self valueForKeyEx:TYPE_KEY];
    if (type == nil)
    {
        return @"";
    }
    
    switch (type.integerValue)
    {
        case RepeatTypeDaily:
            return REPEAT_DAILY;
        case RepeatTypeWeekly:
            return REPEAT_WEEKLY;
        case RepeatTypeEach2Week:
            return REPEAT_EACH_2_WEEK;
        case RepeatTypeMonthly:
            return REPEAT_MONTHLY;
    }
    
    return @"";
}

@end

@implementation UILocalNotification(Extension)

/*
 App launch or open
 1. fetch new item today and insert
 2. Cancel all notifications
 
 App go to background
 1. when the app will terminate, calculate next notification and badge
 */
+ (void)scheduleNotificationWithAlertBody:(NSString*)body
                                 fireDate:(NSDate*)fireDate
                              badgeNumber:(NSInteger)badgeNumber
             isCancelAllLocalNotification:(BOOL)cancel
{
    // Schedule the notification
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = fireDate;
    localNotification.alertBody = body;
    
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.applicationIconBadgeNumber = badgeNumber;
    
    if (cancel)
    {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    }
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

@end